package eu.connect.im;

import java.util.LinkedList;

public class MessageQueue
{
	private LinkedList<Message> msgQueue;
	private boolean shutdown;
	
	public MessageQueue()
	{
		this.msgQueue = new LinkedList<Message>();
	}
	
	public void addMessage(Message msg)
	{
		if (!this.shutdown)
		{
			synchronized (this.msgQueue)
			{
				this.msgQueue.addLast(msg);
				this.msgQueue.notify();
			}
		}
	}
	
	public Message waitForMessage()
	{
	    Message msg = null;
	    try
	    {
	    	if (!this.shutdown)
	    		synchronized (this.msgQueue)
	    		{
	    			if ((this.msgQueue.size() == 0) && (!this.shutdown))
	    				this.msgQueue.wait();
	    			if ((this.msgQueue.size() > 0) && (!this.shutdown))
	    				msg = (Message)this.msgQueue.removeFirst();
	    		}
	    }
	    catch (InterruptedException ex) {
	    }
	    return msg;
	}
	
	public void shutdown()
	{
		this.shutdown = true;
		synchronized (this.msgQueue) {
			this.msgQueue.notifyAll();
		}
	}
	
	public void start()
	{
		this.shutdown = false;
	}
	
	public boolean isRunning()
	{
		return !this.shutdown;
	}

}
